<template>
  <van-cell-group>
    <template v-for="(item, index) in formItemList" :key="item.props.name || index">
      <template v-if="$slots[item.props.name]">
        <slot :name="item.props.name" v-bind="item"></slot>
      </template>
      <FormItem
        v-else
        v-model="modelValue[item.props.name]"
        :props="item.props"
        :on="item.on"
        :type="item.type"
      >
        <template #input v-if="$slots[item.props.name + '-input']">
          <slot :name="item.props.name + '-input'" v-bind="item"></slot>
        </template>
      </FormItem>
    </template>
  </van-cell-group>
</template>
<script setup>
import FormItem from './FormItem.vue'

const props = defineProps({
  modelValue: { type: Object, default: () => {} },
  json: {
    type: Array,
    default: [],
  },
})

const formItemList = computed(() => {
  return props.json.map(options => {
    const required = options.required
    const type = options.type || 'text'
    const on = options.on || {} // 不能执行delete options.on，会导致内部函数地址也被删除
    let rules = options.rules || []

    switch (type) {
      case 'text':
        if (!options.placeholder) options.placeholder = `请输入${options.label}`
        if (required) rules = [{ required: true, message: `请输入${options.label}` }, ...rules]
        break
      case 'radio':
        if (required) rules = [{ required: true, message: `请选择${options.label}` }, ...rules]
        break
      case 'select':
        if (!options.placeholder) options.placeholder = `请选择${options.label}`
        if (required) rules = [{ required: true, message: `请选择${options.label}` }, ...rules]
        break
      default:
        break
    }

    return {
      type,
      props: {
        ...options,
        rules,
      },
      on,
    }
  })
})
</script>
<style lang="scss" scoped></style>
